from utils.database import db
import time
import os
import json
import subprocess
from datetime import datetime, timedelta
from control.runtime import runtime
from control.server import server
import asyncio
from loguru import logger

class AppService:
    def __init__(self):
        self.init_database()
        # 存储运行中的应用进程
        self.running_processes = {}
        self.app_tokens = {"grass":"xxxxx"}  # {app_key: token}

    def init_database(self):
        """初始化数据库表"""
        create_table_sql = """
        CREATE TABLE IF NOT EXISTS t_installed_app (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            app_key TEXT NOT NULL,
            app_name TEXT NOT NULL,
            app_icon TEXT,
            app_path TEXT,
            description TEXT,
            expire_time DATETIME,
            cost DECIMAL(10,2) DEFAULT 0,
            create_time DATETIME DEFAULT (datetime('now', 'localtime')),
            update_time DATETIME DEFAULT (datetime('now', 'localtime')),
            config TEXT DEFAULT '{}',
            status TEXT DEFAULT 'stopped',
            UNIQUE(app_key)
        );
        """
        create_trigger_sql = """
        CREATE TRIGGER IF NOT EXISTS tr_installed_app_update 
        AFTER UPDATE ON t_installed_app
        BEGIN
            UPDATE t_installed_app SET update_time = datetime('now', 'localtime')
            WHERE id = NEW.id;
        END;
        """
        
        with db:
            db.create_table(create_table_sql)
            db.create_table(create_trigger_sql)

    def get_installed_app_list(self, request=None):
        """获取已安装的应用列表"""
        with db:
            sql = """
            SELECT 
                id,
                app_key,
                app_name,
                app_icon,
                description,
                expire_time,
                cost,
                config,
                create_time,
                update_time
            FROM t_installed_app
            ORDER BY update_time DESC
            """
            apps = db.query(sql, mapper=[
                {'field': 'id', 'type': 'number'},
                {'field': 'key', 'type': 'string'},
                {'field': 'name', 'type': 'string'},
                {'field': 'icon', 'type': 'string'},
                {'field': 'description', 'type': 'string'},
                {'field': 'expiryDate', 'type': 'date'},  
                {'field': 'cost', 'type': 'number'},
                {'field': 'config', 'type': 'json'},
                {'field': 'createTime', 'type': 'time'},  
                {'field': 'updateTime', 'type': 'time'}   
            ])
            
            # 添加运行时状态
            for app in apps:
                app['status'] = runtime.get_app_status(app['key'])
            
            return apps if apps else []

    def configure_app(self, request):
        """配置应用
        request: {
            app_key: str,
            config: dict
        }
        """
        try:
            app_key = request['app_key']
            config = request.get('config', {})
            
            # 更新数据库中的配置
            with db:
                db.execute(
                    "UPDATE t_installed_app SET config = ? WHERE app_key = ?",
                    (json.dumps(config), app_key)
                )
            
            # 如果应用正在运行，发送配置更新
            if app_key in self.app_tokens:
                token = self.app_tokens[app_key]
                asyncio.run(server.update_config(token, config))
            
            return {'success': True, 'message': '配置已更新'}
        except Exception as e:
            return {'success': False, 'message': f'配置更新失败: {str(e)}'}

    def uninstall_app(self, request):
        """卸载应用
        request: {
            app_key: str
        }
        """
        try:
            # 先停止应用如果正在运行
            self.stop_app({'app_key': request['app_key']})
            
            with db:
                # 获取应用路径
                app_path = db.query_one(
                    "SELECT app_path FROM t_installed_app WHERE app_key = ?", 
                    (request['app_key'],)
                )
                
                # 删除应用记录
                result = db.execute(
                    "DELETE FROM t_installed_app WHERE app_key = ?",
                    (request['app_key'],)
                )
                
                # 如果有安装目录，尝试删除
                if app_path and app_path[0] and os.path.exists(app_path[0]):
                    try:
                        os.remove(app_path[0])  # 如果是单文件
                    except:
                        try:
                            import shutil
                            shutil.rmtree(app_path[0])  # 如果是目录
                        except Exception as e:
                            return {'success': True, 'message': f'应用记录已删除，但清理文件失败: {str(e)}'}
                
                return {'success': result, 'message': '卸载成功' if result else '应用不存在'}
        except Exception as e:
            return {'success': False, 'message': f'卸载失败: {str(e)}'}

    def renew_app(self, request):
        """续费应用
        request: {
            app_key: str,
            months: int
        }
        """
        try:
            with db:
                # 获取当前过期时间
                current_expire = db.query_one(
                    "SELECT expire_time FROM t_installed_app WHERE app_key = ?",
                    (request['app_key'],)
                )
                
                if not current_expire:
                    return {'success': False, 'message': '应用不存在'}
                
                # 计算新的过期时间
                try:
                    current_date = datetime.strptime(current_expire[0], '%Y-%m-%d')
                except:
                    current_date = datetime.now()
                
                new_expire = current_date + timedelta(days=30 * request.get('months', 1))
                
                # 更新过期时间
                result = db.execute(
                    "UPDATE t_installed_app SET expire_time = ? WHERE app_key = ?",
                    (new_expire.strftime('%Y-%m-%d'), request['app_key'])
                )
                
                return {'success': result, 'message': '续费成功' if result else '续费失败'}
        except Exception as e:
            return {'success': False, 'message': f'续费失败: {str(e)}'}

    def start_app(self, request):
        """启动应用
        request: {
            app_key: str
        }
        """
        try:
            with db:
                # 获取应用信息
                sql = """
                    SELECT app_path, expire_time 
                    FROM t_installed_app 
                    WHERE app_key = ?
                """
                app_info = db.query_one(sql, 
                    params=(request['app_key'],),
                    mapper=[
                        {'field': 'app_path', 'type': 'string'},
                        {'field': 'expire_time', 'type': 'date'}  # 只需要比较日期
                    ]
                )
                logger.info("获取到app信息:{}", app_info)
                if not app_info:
                    return {'success': False, 'message': '应用不存在'}
                
                app_path = app_info['app_path']
                expire_time = app_info['expire_time']
                
                # 检查是否过期
                # if expire_time:
                #     today = datetime.now().strftime('%Y-%m-%d')
                #     if expire_time < today:
                #         return {'success': False, 'message': '应用已过期，请续费'}
                
                # 检查应用是否已经在运行
                if request['app_key'] in self.running_processes:
                    return {'success': True, 'message': '应用已在运行'}
                
                # 启动应用
                if app_path and os.path.exists(app_path):
                    try:
                        # 生成token
                        token = server.generate_token()
                        self.app_tokens[request['app_key']] = token
                        
                        # 启动进程
                        process = subprocess.Popen(
                            [app_path, token],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE
                        )
                        self.running_processes[request['app_key']] = process
                        
                        return {'success': True, 'message': '应用启动成功'}
                    except Exception as e:
                        return {'success': False, 'message': f'应用启动失败: {str(e)}'}
                else:
                    return {'success': False, 'message': '应用文件不存在'}
        except Exception as e:
            return {'success': False, 'message': f'启动失败: {str(e)}'}

    def stop_app(self, request):
        try:
            logger.info("关闭后台脚本请求参数:{}", request)
            app_key = request['app_key']
            asyncio.run(server.send_command("aaa", 'stop'))
            if app_key in self.app_tokens:
                token = self.app_tokens[app_key]
                asyncio.run(server.send_command(token, 'stop'))
            if app_key in self.running_processes:
                logger.info("关闭后台脚本:{}", app_key)
                process = self.running_processes[app_key]
                process.terminate()
                process.wait(timeout=5)  # 等待进程结束
                del self.running_processes[app_key]
                
            if app_key in self.app_tokens:
                del self.app_tokens[app_key]
            return {'success': True, 'message': '应用已停止'}
        except Exception as e:
            return {'success': False, 'message': f'停止失败: {str(e)}'}

    def get_app_store_list(self, request):
        return [
            {
                'id': 1,
                'name': 'AI文章助手',
                'description': '智能生成高质量文章，支持多种文体和风格',
                'icon': 'https://placeholder.co/100',
                'category': 'AI助手',
                'rating': 4.5,
                'downloads': 1234,
                'price': 0,
                'installed': False,
                'tags': ['hot', 'free']
            },
            {
                'id': 2,
                'name': '数据可视化Pro',
                'description': '专业的数据分析和可视化工具，支持多种图表类型',
                'icon': 'https://placeholder.co/100',
                'category': '数据分析',
                'rating': 4.8,
                'downloads': 3456,
                'price': 99,
                'installed': True,
                'tags': ['hot', 'paid']
            },
            {
                'id': 3,
                'name': '代码生成器',
                'description': '快速生成各类代码模板，提高开发效率',
                'icon': 'https://placeholder.co/100',
                'category': '开发工具',
                'rating': 4.2,
                'downloads': 2345,
                'price': 0,
                'installed': False,
                'tags': ['new', 'free']
            }
        ]

app_service = AppService()